
var App = require('../common/App.js');
var Notice = require('../service/Notice.js');

/**
* 维护服务器与代理连通性列表 和 记录哪些服务器与代理保持连接
*/

module.exports = new Server2Proxy();

var list = {};
var keepaliveList = {};// {host}:{port} => [ {serverIp},{serverIp} ]

//搜索master 服务器
var masterServerIp = "";
var serverList = App.config.ServerList;
var len = serverList.length;
for(var i=0;i<len;i++){
    var server = serverList[i];
    if(server.master==true){
        masterServerIp = server.host;
        break;
    }
}

function Server2Proxy(){
	//单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }

	
	arguments.callee.instance = this;
}

/**
*
*/
Server2Proxy.prototype.add = function(proxy,serverIp){
    var k = proxy.host+":"+proxy.port;
    if(! (list[k] instanceof Array) ){
        list[k] = [];
    }
    if(! (keepaliveList[k] instanceof Array) ){
        keepaliveList[k] = [];
    }
    if(list[k].indexOf(serverIp)==-1){
        list[k].push(serverIp);

        if(keepaliveList[k].indexOf(serverIp)==-1){
            if(serverIp==masterServerIp){
                keepaliveList[k].unshift(serverIp);
            }else{
                keepaliveList[k].push(serverIp);
            }
        }
        this.keepalive(proxy);
    }
}

/*
*
* 使1台服务器与代理保持连接
*/
Server2Proxy.prototype.keepalive = function(proxy){
    var k = proxy.host+":"+proxy.port;
    if(keepaliveList[k] instanceof Array){
        var len = keepaliveList[k].length;
        if(len == 1){
            return true;
        }
        //第一个不用删除保存连接，因为必须要有一个客户端与代理保持连接。而且主要保持连接的客户端都会放在第一个位置
        for(var i=1;i<len;i++){
            Notice.delKeepalive(keepaliveList[k][i],proxy);
        }
        keepaliveList[k] = [ keepaliveList[k][0] ];
    }
    return true;

}

/**
*
* 删除代理
*/
Server2Proxy.prototype.del = function(proxy){
	var k = proxy.host+":"+proxy.port;
	var kList = keepaliveList[k];
	if(kList[k] instanceof Array){
		var len = kList[k].length;
		for(var i=0;i<len;i++){
            console.log("delete proxy keepalive ",proxy);
			Notice.delKeepalive(keepaliveList[k][i],proxy);
		}
	}
	delete keepaliveList[k];

	delete list[k];
}

/**
*
* 返回与指定代理 能连接上的服务器列表
*/
Server2Proxy.prototype.getServerList = function(proxy){
    var k = proxy.host+":"+proxy.port;
	var serverList = [];
    if(list[k] instanceof Array){
		serverList = list[k]
	}
    return serverList;
}

Server2Proxy.prototype.getAllList = function(){
    return {"list":list,"keepaliveList":keepaliveList};
}

